/**
 * 流程标题右侧按钮区
 */
import React, { useEffect, useState, useRef, useLayoutEffect } from 'react';
import { reloadField, useForm } from "../../framework/common/context/metadata-context";
import request from "../../framework/common/utils/request";
import {getQuery, buildUrl ,openWin, fileIsUploading, isObject} from "../../framework/common/utils"
import myMessage from "../../framework/common/utils/message"
import { message, Modal } from "antd";
import qs from "qs"
import clsx from "clsx";
import ProcessInfo from "./ProcessInfo1.js";
import ModalCirculateProcess from "./ModalCirculateProcess.js"//传阅弹出框
import ModalUrgent from "./ModalUrgent.js"//催办弹出框
import ModalWithdraw from "./ModalWithdraw.js"//撤回弹出框
import cloneDeep from "lodash/cloneDeep";
import getInitiateFormData, {getApproveDraftData} from '../../framework/common/utils/getInitiateFormData';//获取流程表单数据
// import { deleteGroupRow, revalidateSubGroup, triggerGroupRowRule, triggerSqlAPIValueCaculate } from '../../framework/common/rule/setRuleResult';
import jQuery  from 'jquery'
import { formReload } from '../../framework/common/rule/setRuleResult';
import eventBus from '../../framework/common/eventBus';
import isArray from "lodash/isArray"

//打印
function print({
    tplData,
    params,
    urlPrefix
}){
    var urlParams = getQuery();
    if (tplData.form.print_addr) {
        openWin(tplData.form.print_addr);
        return;
    }
    var url = '/flowinstance/approval/preview';
    if (urlParams.proc_id) {
        url += '?proc_id=' + urlParams.proc_id;
        url += '&node_id=' + (urlParams.node_id || params.node_id || '');
    } else {
        url += '?flow_template_id=' + params.flow_template_id;
        if (params.ParentProcess) {
            url += '&is_sub_process=1';
        }
    }
    if (urlParams['open_type']) {
        url += '&open_type=' + urlParams['open_type']
    }
    if (urlParams['package_id']) {
        url += '&package_id=' + urlParams['package_id']
    } else {
        url += '&package_id=' + tplData.form.form_data.packageInfo.id
    }
    if (!params.ParentProcess) {
        url += '&business_id=' + tplData.ProcessInfo['BusinessGuid'];
        if (urlPrefix) {
            url = urlPrefix + url;
        }
    }
    openWin(url);
}

//检查erp中转页面是否存在
function checkHtmlFile(opt){

    if(!opt){
        return;
    }
    if(!opt.url){
        return;
    }

    if(jQuery("#js-check-htmlfile").length){//先移除标签
        jQuery("#js-check-htmlfile").remove(); 
    }
    
    //创建link标签，判断当前iframe是否存在
    var link = document.createElement('link');
    link.id = "js-check-htmlfile";
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = opt.url;// 这里设置需要检测的url;
    link.onerror = function () {
 
        jQuery("#js-check-htmlfile").remove();//状态404后移除标签
        opt.onerror && opt.onerror();
    }
    link.onload = function () {

        jQuery("#js-check-htmlfile").remove();//移除标签
        opt.onload && opt.onload();
    }

    document.body.appendChild(link);//添加link到页面
}

//查看业务数据
function viewBusiness({
    btnInfo,
    tplData,
    params
}){
    var btnid = btnInfo.Id;
    if(!btnid){//如果没有ID信息，不做处理
        console.log("查看业务对象需要Id信息")
        return;
    }
    var btnObj = null;
    tplData.BusinessButtons.BusinessButtonList.find(function(btn){
        if(btn.Id == btnid){
            btnObj = btn;
        }
    })
    if(!btnObj){
        tplData.BusinessButtons.MoreButtonList.find(function(btn){
            if(btn.Id == btnid){
                btnObj = btn;
            }
        })
    }

    var openUrl = btnObj.OpenUrl;
    var app_id = btnObj.AppId;
    // 请求获取最新的认证地址
    let requestOption = {
        url: "/flowcenter/form-ctrl/build-authed-url",
        method: 'POST',
        data: {
            "app_id": app_id,
            "mode": 0,
            "originUrl": openUrl,
            "business_id":params.business_id,
            "proc_id":tplData.ProcessInfo.ProcessGuid,
            "package_id":tplData.package_id
        },
        noTip: true//请求错误时，axios不展示公共错误
    }
    request(requestOption).then(function(ret) {
        if (ret.code === 1) {
            if (ret.data.openType == 1) {//如果是老的修改业务数据
                openWin(ret.data.url);
            }else{
                openWin(ret.data);
            }
        }else{
            let errorMsg = ret.message || "获取查看地址出错";
            message.error(errorMsg);
        }
    }).catch(function(){
        message.error("获取查看地址出错");
    });
}

//流程详情弹框展示
function showDetailContent({
    tplData
}){
    Modal.info({
        icon: null,
        title:"流程详情",
        width: 400,
        centered: true,
        okText:"关闭",
        content:<ProcessInfo key={1} tplData={tplData}></ProcessInfo>
    })
}

//更新业务数据信息
function saveformDataObject({
    params,
    param,
    tplData
}){
    if(window._saveWfiTime){
        clearTimeout(window._saveWfiTime);
    }
    window._saveWfiTime = setTimeout(function(){
        if(!param){
            param = getApproveDraftData({
                params: params, 
                tplData: tplData
            });
        }
        param.proc_id = tplData.ProcessInfo.ProcessGuid;
        param.node_id = tplData.NodeInfo.node_id || getQuery().node_id;
        request({
            url: '/flowinstance/approval/save-wfi-table-object',
            method: 'POST',
            data: param,
            noTip:true
        }).then(
            function(result){
                if(result.code == 1){
                    params.table_val_md5 = result.data.table_val_md5;
                }
            }
        );
    }, 1000);
}

//保存草稿
function dowhat({
    tplData,
    params,
    urlPrefix,
    isApproveSave = false,//是否审批中暂存
    showConfirm = true,//暂存成功后，是否显示提示
    isDataChange = false,//修改业务数据后触发的保存草稿
    spinTip//全局遮罩提示语
}) {
    if (isApproveSave) {//审批中 暂存
        var param = getApproveDraftData({
            params: params, 
            tplData: tplData
        });//获取审批中需要暂存的信息
    } else {//发起|草稿 保存草稿
        var param = getInitiateFormData({
            params: params, 
            tplData: tplData, 
            approveType: tplData.__approveType__,
            type: 'Draft'
        });
        if(param === false){//收集数据校验没成功
            return;
        }
    }
    var url = '/flowinstance/process/save-draft?prc_name=' + param.title;
    var message = "暂存成功，可以到『我发起的流程』模块查看该流程。是否关闭当前窗口？";
    if (isApproveSave) {
        url = '/flowinstance/approval/save-draft';
        message = "暂存成功，可以到『我办理的流程』模块查看该流程。是否关闭当前窗口？";
    }

    if(params.IsSubProc){
        message = "暂存成功，可以到『我办理的流程』模块查看该流程。是否关闭当前窗口？";
    }
    
    eventBus.publish('screen.lock', {
        spinning: true,
        tip: spinTip

    });//全局遮罩

    request({
        url: url,
        method: 'POST',
        data: param,
        noTip: true//请求错误时，axios不展示公共错误
    }).then(function(result) {
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩
        
        if (result.code == 1) {
            if(showConfirm){//如果开启了显示提示，提示错误信息，发起业务数据为不开启，不提示已保存草稿
                Modal.confirm({
                    icon: null,
                    title: "提示",
                    centered: true,
                    content: message,
                    onOk() {
                        window.opener = null;
                        window.open('', '_self', '');
                        window.close();
                    },
                    onCancel(){
                        if (!isApproveSave && !params.IsSubProc) {
                            var url = "/flowinstance/process/create?proc_id=" + result.data.proc_id;
                            // var url = "/frontend/build?create=1&proc_id=" + result.data.proc_id;
                            if (urlPrefix) {
                                url = urlPrefix + url;
                            }
                            window.location.href = url;
                        }
                    }
                });
            }
        } else {
            if(showConfirm){//如果开启了显示提示，提示错误信息，发起业务数据为不开启，错了也不要提示出来
                if (result.code == 30057 || result.code == 30051) {
                    myMessage.info({
                        icon: null,
                        //title:"流程详情",
                        width: 400,
                        centered: true,
                        okText:"我知道了",
                        content: result.message
                    });
                    return;
                }
                myMessage.info({
                    icon: null,
                    //title:"流程详情",
                    width: 400,
                    centered: true,
                    okText:"关闭",
                    content: "保存草稿失败"
                });
            }
        }
    },function(){
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩
        
        if(showConfirm){
            myMessage.info({
                icon: null,
                //title:"流程详情",
                width: 400,
                centered: true,
                okText:"关闭",
                content: "保存草稿失败"
            });
        }
    })
    
    //修改业务数据触发的暂存
    if(isDataChange){
        saveformDataObject({
            tplData: tplData,
            params: params,
            param: param
        });//更新流程中心的业务数据信息
    }
};
function saveDraft({
    tplData,
    params,
    urlPrefix,
    isApproveSave, //是否审批中保存草稿，只有发起|草稿，才为true，其他场景都需要false
    showConfirm,//保存草稿后，是否需要提示信息
    isDataChange = false,//修改业务数据后触发的保存草稿
    spinTip="保存中"
}){

    // 发起页面保存草稿，如果isApproveSave传的是true说明是异常请求
    if((!tplData.ApproveSteps || tplData.ApproveSteps.length == 0) && isApproveSave){
        return
    };

    if(isDataChange === true){//修改业务数据导致的保存草稿，不做文件上传中校验
        
    }else{
        //验证是否有上传中的附件
        let fileUploadingRes = fileIsUploading({
            tipMessage: "文件正在上传，请稍后操作。"
        })
        if(fileUploadingRes){
            return false;//存在上传中的附件不做后续校验
        }
    }
    
     //tplData.form.form_mode == 0 或者 null 说明是普通表单 否则是外挂表单
    if (tplData.form.form_mode == 0 || tplData.form.form_mode == null) {
        //流程中心表单直接保存
        dowhat({
            tplData: tplData,
            params: params,
            urlPrefix: urlPrefix,
            isApproveSave: isApproveSave,//是否审批中暂存
            showConfirm: showConfirm,
            isDataChange: isDataChange,
            spinTip: spinTip
        });
    } else { 
        //外挂表单
        var $cf = jQuery("#form-runtime");
        var showErr = function(errmsg) {
            if (errmsg) {
                myMessage.info({
                    content: errmsg
                });
            }
        };
        $cf.getFormData(
            function() {
                //先调用外挂表单保存草稿接口，外挂表单可能会校验必填
                $cf.saveCustomFormData(function() {
                    dowhat({
                        tplData: tplData,
                        params: params,
                        urlPrefix: urlPrefix,
                        isApproveSave: isApproveSave,//是否审批中暂存
                        showConfirm: showConfirm,
                        isDataChange: isDataChange,
                        spinTip: spinTip
                    });
                }, showErr, isApproveSave ? 'Approve' : 'Initiate');
            }, 
            function(errmsg) {
                myMessage.info({
                    content: errmsg
                });
            }
        );

        
    }
}

//移除计算字段数据
function __removeCalculationData({
    data,
    tplData
}){
    //移除主表内的计算字段数据
    isObject(data.main) && Object.keys(data.main).forEach(function(fieldCode){
        if(tplData.__calculationFields__.main[fieldCode]){
            delete data.main[fieldCode];
        }
    });

    //移除子表内的计算字段数据
    isObject(data.children) && Object.keys(data.children).forEach(function(groupCode){//1.遍历同步到子表分组
        let groupData = data.children[groupCode];
        isArray(groupData) && groupData.forEach(function(rowData){//2.遍历子表的每行数据
            if(rowData.status == "update" || rowData.status == "add"){//当前行数据是更新或者新增
                isObject(rowData.field) && Object.keys(rowData.field).forEach(function(fieldCode){//3.遍历每一列数据
                    if(tplData.__calculationFields__.children?.[groupCode]?.[fieldCode]){//如果当前字段是计算字段
                        delete rowData.field[fieldCode];//移除数据
                    }
                });
            }
        });
    });
    return data;
}

//发送请求获取业务系统表单数据，并更新表单
function formDataReload({
    form,
    tplData,
    params,
    success, //获得到表单数据后的回调方法
    error,//请求失败后的回调
    type = false//默认为false，修改业务数据：'data_change'，发起/重新发起：目前没有传递这个参数
}){

    if(jQuery("#js-open-erp-edit-business").length){
        jQuery("#js-open-erp-edit-business").remove();//移除打开erp的iframe
    }

    var param = {
        package_id: params.package_id,
        business_id: tplData.ProcessInfo.BusinessGuid,
        form_data_md5: tplData.form_data_md5 || "",//用于后端对比流程中心表单和业务系统表单数据是否一致
        form_data: {
            main:tplData.form.form_data.main,
            children:tplData.form.form_data.children,
            attachments:tplData.form.form_data.attachments,
            attachmentTypes:tplData.form.form_data.attachmentTypes,
        },
        // file_sort:params.file_sort,
        data_control: tplData.form.data_control,
        relation_process: tplData.RelationProcess.RelationProcessList, //相关流程
        proc_id: tplData.ProcessInfo.ProcessGuid
    };
    if (type === "data_change") {//修改业务数据的同步，需要作为参数传递给后端
        param.type = type
    }

    let requestOption = {
        url: "/flowinstance/approval/form-data-reload",
        method: 'POST',
        data: param,
        needCancelToken: true,
        noTip: true//请求错误时，axios不展示公共错误
    }
    request(requestOption).then(function(result) {
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩
        if (result.code === 1) {
            // 测试代码，后端返回的数据结构如下
            // result.data.main = {
            //     jisuan1: 33333333333,
            //     nullNumberShowNothing: 33333333333
            // }
            // result.data.children = {
            //     table: [
            //         {
            //             field:{
            //                 jisuan1: 33333333333,
            //                 nullNumberShowNothing: 33333333333
            //             },
            //             obj_id: "32132132",
            //             status: "add"
            //         }
            //     ]
            // }
            result.data = __removeCalculationData({
                data: result.data,
                tplData: tplData
            });//移除计算字段结果

            if(type === "data_change" || true){//修改业务数据的同步，直接更新，不给提示，暂时不走提示逻辑，只要同步成功，就做一次数据回填
                formReload(form, result.data);//表单更新数据

                if (success) {//请求成功后回调
                    success();//保存草稿
                }
            }else{//其他场景，需要给出提示，选择取消后才进行同步
                let resultData = result.data;//后端返回值
                if(
                    resultData.attachments//同步到的附件信息，有数据是[]，无数据是undefined
                    || resultData?.relation_process?.length > 0 //同步到的关联流程
                    || Object.prototype.toString.call(resultData?.main) === "[object Object]"//同步到的主表字段，无数据是[]，有数据是{...}
                    || Object.prototype.toString.call(resultData?.children) === "[object Object]"//同步到的子表字段，无数据是[]，有数据是{...}
                ){//附件、关联流程、主表、子表时，表示未发生变化
                   
                    myMessage.confirm({
                        okType: "default",
                        title: "提示",
                        content: "检测到业务系统数据已更新，是否要更新表单数据？如选择“更新”，表单将刷新，已填写内容将不会保留，请谨慎操作；如选择“忽略”，将以当前表单数据为准继续发起流程。",
                        cancelText:"更新",
                        onCancel:function(){//点取消按钮，刷新页面，后端会自动再同步一次
                            window.location.reload();
                        },
                        okText:"忽略",
                        onOk:function(){//点确定按钮，直接发起不要做前端数据同步
                            if (success) {//请求成功后回调
                                success();//保存草稿|发起
                            }
                        }
                    })
                }else{
                   //后端未返回数据，直接调用后续逻辑
                    if (success) {//请求成功后回调
                        success();//保存草稿
                    }
                }
            }
        }
        else{
            let errorMsg = result.message || "请求出错";
            message.error(errorMsg);
        }
    },function(){
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩
        error?.();//请求失败后回调方法
    }).catch(function(e){
        console.log('表单验证失败',e)
    });

}

//更新业务数据，并给出loading提示
function __ReloadFormAndSaveDraft({
    form,
    tplData: tplData,
    params: params,
    urlPrefix: urlPrefix,
}){
    eventBus.publish('screen.lock', {
        spinning: true,
        tip: "同步业务数据中"
    });//全局遮罩
    //不管点不点更新数据，只要这个弹出框被销毁，就会触发form reload
    formDataReload({
        form,
        tplData: tplData,
        params: params,
        urlPrefix: urlPrefix,
        success:function(){
            if(tplData.ApproveSteps && tplData.ApproveSteps.length){//存在审批步骤才暂存，也就是发起/草稿步骤，不会暂存
                eventBus.publish('screen.lock', {
                    spinning: true,
                    tip: "同步业务数据完成，暂存中"
                });//全局遮罩
                saveDraft({
                    tplData: tplData,
                    params: params,
                    urlPrefix: urlPrefix,
                    isApproveSave: true,//审批中保存草稿
                    showConfirm: false,//保存草稿后，不提示成功信息
                    isDataChange: true//修改业务数据后触发的保存草稿
                });
            }
        },
        type: 'data_change'
    });
}

//erp给路程中心发消息格式
//1、erp通知流程中心关闭修改业务数据窗口并刷新流程中心表单
//1.1、如果是iframe弹出框形式
/*
var postData = {
    type: "workflow_close_business_win"
}
try{
    parent.postMessage(JSON.stringify(postData), "*");//保留iframe嵌套修改业务数据方式
}catch(e){

}
//1.2、如果是浏览器新标签页形式
try{
    //opener.postMessage(JSON.stringify(postData), "*");
    if(opener.workflow_close_business_win){
        opener.workflow_close_business_win();//兼容window.open打开修改业务数据方式，关闭工作流的修改业务数据弹出框
    }
}catch(e){

}
*/
//绑定postMesage，监听业务系统的消息
let bussinessEvent = {
    eventName: 'message.business',
    bind: function({
        form,
        tplData,
        params,
        urlPrefix,
        args
    }) {
        console.log("===");
        console.log("修改业务数据，erp可编辑的字段")
        console.log(args);
        console.log("===");
        jQuery(window).off(this.eventName).on(this.eventName, function(evt) {
        
            //chrome浏览器dev tools会发消息
            if(evt.originalEvent.data?.source === "react-devtools-bridge" || evt.originalEvent.data?.source === 'react-devtools-content-script' || evt.originalEvent.data?.type==="webpackInvalid"){
                
                return ;
            }
            var result;

            try {
                result =jQuery.parseJSON(evt.originalEvent.data);
                if (!result) {
                    return;
                }
            } catch (e) {
                console.error(e);
                return;
            }
            console.log("result.type",result.type)
            switch (result.type) {
                case 'workflow_pull_business_data':
                    args.BT_DomainXML = '';
                    evt.originalEvent.source.postMessage(JSON.stringify({
                        type: 'workflow_push_business_data',
                        data: args
                    }), "*");
                    break;
                case 'workflow_close_business_win'://erp发消息关闭流程中心模态弹出框。注意：这里会关闭并刷新表单
                    //存在两种打开方式，所以需要两种方式都兼容    

                    //1.关闭window.open的弹出框
                    if(window.layerwinOpenErpBusiness){
                        //如果存在弹框，弹框的end事件会触发表单刷新
                        window.layerwinOpenErpBusiness.destroy?.()
                        delete window.layerwinOpenErpBusiness;
                    }

                    //2.关闭iframe模式的模态窗
                    //给修改业务数据弹框组件发送消息关闭弹窗，并绑定弹出框关闭时事件
                    eventBus.publish("modalDataChange.update", {
                        modalShow: false
                    })

                    break;
                case "workflow_reloadform"://刷新表单

                    if(window.layerwinOpenErpBusiness){
                        //如果存在弹框，弹框的end事件会触发表单刷新
                        window.layerwinOpenErpBusiness.destroy?.()
                        delete window.layerwinOpenErpBusiness;
                    }else{
                        //不存在弹框，则直接触发表单刷新
                        __ReloadFormAndSaveDraft({
                            form: form,
                            tplData: tplData,
                            params: params,
                            urlPrefix: urlPrefix,
                        })
                    }
                    break;
            }
        });
    },
    unbind: function() {
        jQuery(window).off(this.eventName);
    }
}
//修改业务数据
function dataChange({
    form,
    tplData,
    params,
    urlPrefix,
    csrfToken
}){
    var data = tplData.data_change.form_data_reload;
    data.form_data = params.form_data;
    data.data_control = tplData.form.data_control;

    // 计算高度
    var height = window.innerHeight  * 0.94;
    var urlParams = qs.parse(tplData.data_change.url, { ignoreQueryPrefix: true });
    var minHeight;

    if (urlParams.wfMinHeight) {
        urlParams.wfMinHeight = parseInt(urlParams.wfMinHeight);
        minHeight = urlParams.wfMinHeight + 50;
    }

    if (height <= minHeight) {
        height = minHeight;
    }
    var openUrl = tplData.data_change.url;
    var app_id = tplData.data_change.app_id;
    var mode = tplData.data_change.mode;

    var needFormData = 0;
    //核心erp
    if(tplData.form && tplData.form.form_data.appInfo.api_adapter_id == 'ae56a07dc20b485891e058a719c2e8a5'){
        needFormData = 1;
    }

    let requestOption = {
        url: "/flowcenter/form-ctrl/build-authed-url",
        method: 'POST',
        data: {
            "app_id": app_id,
            "data_change_mode": mode,
            "mode": 0,
            "originUrl": openUrl,//tplData.data_change.url
            "business_id":params.business_id,
            "proc_id":tplData.ProcessInfo.ProcessGuid,
            "package_id":tplData.package_id,
            "form_data":needFormData == 1 ? tplData.form.form_data:"" //核心erp才传递表单信息（btXml）
        },
        noTip: true//请求错误时，axios不展示公共错误
    }
    request(requestOption).then(function(ret) {
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩

        //测试数据
        // ret = {
        //     code:1,
        //     data:{
        //         openType: 2,
        //         //url: "http://xulongchang.gitee.io/jianli/test2.html",
        //         //url: ret.data,//erp修改业务数据页面
        //         jumpurl:"http://xulongchang.gitee.io/jianli/test.html"//打开erp站点的中转页
        //     }
        // }
        // ret.data = "http://xulongchang.gitee.io/jianli/test2.html"

        if (ret.code === 1) {
            if (ret.data.openType == 1) {//如果是老的修改业务数据
                window.modifyBusinessDataDomain = tplData.data_change.data_range;
                ret.data.url = ret.data.url
                    + "&workflowdomain=" + encodeURIComponent(window.location.origin)
                    + "&processguid=" + tplData.ProcessInfo.ProcessGuid
                    + "&businessguid=" + tplData.ProcessInfo.BusinessGuid
                window.open(ret.data.url);
                return;
            }

            //绑定postmessage监听，用于跟erp进行前端交互
            bussinessEvent.bind({
                form: form,
                tplData: tplData,
                params: params,
                urlPrefix: urlPrefix,
                csrfToken: csrfToken,
                args: jQuery.extend({}, {
                    ModifyBusinessDataDomain: tplData.data_change.data_range
                }, {
                    CrossBussinessUrl: tplData.data_change.url
                })
            });

            if(ret.data.openType == 3){//如果是window.open方案打开修改业务数据方案

                //往页面追加iframe，用于打开修改业务数据页面
                if(jQuery("#js-open-erp-edit-business").length){
                    jQuery("#js-open-erp-edit-business").remove();
                }
                // MyWorkflow/CrossDomainOpenErp.html erp用于打开修改业务数据的中转页面
                var _url = tplData.ServerAddr + "/MyWorkflow/CrossDomainOpenErp.html?backurl=" + encodeURIComponent(ret.data.url);
                var $iframe = jQuery('<iframe id="js-open-erp-edit-business" class="hideIframe" src="' + _url + '" name="'+ tplData.ProcessInfo.ProcessGuid + '"></iframe>');
                $iframe.appendTo("body");

                checkHtmlFile({
                    url: _url,
                    onerror:function(){
                        //平台未升级，则_url会404，给出升级提示
                        myMessage.info({
                            content: "当前erp版本不支持新窗口修改业务数据，如需支持，请联系管理员！"
                        })
                    },
                    onload:function(){
                        window.layerwinOpenErpBusiness= myMessage.info({
                            okText:"更新数据",
                            afterClose:()=>{
                                eventBus.publish('screen.lock', {
                                    spinning: true,
                                    tip: "同步业务数据中"
                                });//全局遮罩
                                //不管点不点更新数据，只要这个弹出框被销毁，就会触发form reload
                                __ReloadFormAndSaveDraft({
                                    form: form,
                                    tplData: tplData,
                                    params: params,
                                    urlPrefix: urlPrefix,
                                })

                                delete window.layerwinOpenErpBusiness
                            },
                            content:"请在新打开的业务单据窗口编辑数据，确认编辑完毕后，再点击“更新数据”按钮同步业务数据更新审批表单"
                        })
                    }
                });
            }
            else{//iframe打开的方式
                //给修改业务数据弹框组件发送消息，并绑定弹出框关闭时事件
                eventBus.publish("modalDataChange.update", {
                    modalShow: true,
                    title: '修改业务数据',
                    url: ret.data,
                    afterClose: function() {//关闭修改业务数据弹窗后回调，用于更新表单
                        bussinessEvent.unbind();
                        
                        eventBus.publish('screen.lock', {
                            spinning: true,
                            tip: "同步业务数据中"
                        });//全局遮罩

                        //触发form reload
                        __ReloadFormAndSaveDraft({
                            form: form,
                            tplData: tplData,
                            params: params,
                            urlPrefix: urlPrefix,
                        });
                    }
                });

            }
        }
        else{
            let errorMsg = ret.message || "请求出错";
            message.error(errorMsg);
        }
    }, function(){
        eventBus.publish('screen.lock', {
            spinning: false
        });//全局遮罩
    }).catch(function(){
        console.log('请求出错')
    });
}

//更新上一条下一条代办信息
function updateNextNodeUrl({
    tplData,
    setTodoNodeInfo
}) {
    var urlParams = getQuery();
    if (urlParams.afterApprove) {//重新设置上一条下一条代办的afterApprove参数

        if(tplData.TodoNodeInfo.NextNodeUrl){
            tplData.TodoNodeInfo.NextNodeUrl  = buildUrl(tplData.TodoNodeInfo.NextNodeUrl, {
                afterApprove: urlParams.afterApprove
            });//下一条待办链接绑定afterApprove
        }
        if(tplData.TodoNodeInfo.PrevNodeUrl){
            tplData.TodoNodeInfo.NextNodeUrl  = buildUrl(tplData.TodoNodeInfo.PrevNodeUrl, {
                afterApprove: urlParams.afterApprove
            });//上一条待办链接绑定afterApprove
        }
    }
    setTodoNodeInfo(tplData.TodoNodeInfo);//更新上一条下一条代办信息
}

export {
    print,//打印
    checkHtmlFile,
    viewBusiness,//查看业务数据
    showDetailContent,//流程详情弹框展示
    saveDraft,//保存草稿
    formDataReload,//发送请求获取业务系统表单数据，并更新表单
    dataChange,//修改业务数据
    updateNextNodeUrl,//更新上一条下一条代办信息
    saveformDataObject//更新业务数据信息
}